package com.yhao.utils;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;

public class TokenUtil {

    public static String getToken(String userName, long time) {
        String token = AESUtil.encrypt(userName + "." + time);
        return token;
    }

    /**
     * 验证token是否有效，并从中取得username
     * @param token
     * @param redisTemplate
     * @return
     */
    public static String getUserNameFromToken(String token, RedisTemplate redisTemplate) {
        String s = AESUtil.decrypt(token);
        int i = s.lastIndexOf(".");
        String name = s.substring(0, i);
        //验证是否存在此token
        if (redisTemplate.opsForValue().get(name).equals(token)) {
            return name;
        } else {
            return "";
        }

    }

}
